package com.lagou.login.filter;

import org.springframework.boot.web.servlet.server.Session;
import org.springframework.core.annotation.Order;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.util.Arrays;

@WebFilter(filterName = "loginFilter", urlPatterns = "/*")
@Order(1)
public class LoginFilter implements Filter {

    private String[] urls = {"/","/login"};


    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest req = (HttpServletRequest) servletRequest;
        HttpServletResponse response = (HttpServletResponse) servletResponse;
        String url  = req.getRequestURI();
        String user = (String) req.getSession().getAttribute("user");
        if (user == null && !Arrays.asList(urls).contains(url)){
            response.sendRedirect("/");
        }else {
            filterChain.doFilter(servletRequest,servletResponse);
        }
    }

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {

    }

    @Override
    public void destroy() {

    }
}
